/*
 *******************************************************************************
 *
 * Copyright (C) 2019-2020 Dialog Semiconductor.
 * This computer program includes Confidential, Proprietary Information
 * of Dialog Semiconductor. All Rights Reserved.
 *
 *******************************************************************************
 */

package com.dialog.suotalib.suota;

import android.bluetooth.BluetoothDevice;
import android.content.Context;

import com.dialog.suotalib.global.SuotaLibConfig;
import com.dialog.suotalib.global.SuotaLibConfig.Default;
import com.dialog.suotalib.global.SuotaProfile;
import com.dialog.suotalib.interfaces.IBaseSuota;

import java.lang.ref.WeakReference;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;

/**
 * Class that implements a core automated SUOTA
 */
public class AutoSuota {
    private static final String TAG = "AutoSuota";

    private final WeakReference<IBaseSuota> baseSuotaActivityWeakReference;
    private final Lifecycle lifecycle;
    private final SuotaFile suotaFile;
    private final BluetoothDevice bluetoothDevice;
    private SuotaManager suotaManager;

    public AutoSuota(Lifecycle lifecycle, @NonNull IBaseSuota baseSuota, @NonNull SuotaFile suotaFile, @NonNull BluetoothDevice bluetoothDevice) {
        baseSuotaActivityWeakReference = new WeakReference<>(baseSuota);
        this.lifecycle = lifecycle;
        this.suotaFile = suotaFile;
        this.bluetoothDevice = bluetoothDevice;
    }

    public IBaseSuota getBaseSuotaActivity() {
        return baseSuotaActivityWeakReference.get();
    }

    public SuotaManager getSuotaManager() {
        return suotaManager;
    }

    public void run(Context context) {
        if (context == null)
            return;

        suotaManager = new SuotaManager(lifecycle, context, bluetoothDevice, new SuotaManagerCallback() {
            @Override
            public void onConnectionStateChange(SuotaProfile.SuotaManagerStatus newStatus) {
                super.onConnectionStateChange(newStatus);
                if (newStatus == SuotaProfile.SuotaManagerStatus.DISCONNECTED && getBaseSuotaActivity() != null) {
                    getBaseSuotaActivity().deviceDisconnected();
                }
            }

            @Override
            public void updateSpeedStatistics(double current, double max, double min, double avg) {
                if (SuotaLibConfig.CALCULATE_STATISTICS)
                    getBaseSuotaActivity().updateSpeedStatistics(current, max, min, avg);
            }

            @Override
            public void onFailure(int errorCode) {
                if (getBaseSuotaActivity() != null)
                    getBaseSuotaActivity().displayErrorDialog(errorCode);
            }

            @Override
            public void onDeviceReady() {
                if (getBaseSuotaActivity() != null)
                    getBaseSuotaActivity().startSuota();
            }

            @Override
            public void onSuotaLog(SuotaProfile.SuotaProtocolState state, SuotaLogType type, String log) {
                if (getBaseSuotaActivity() != null)
                    getBaseSuotaActivity().appendToLogcat(log);
            }

            @Override
            public void onChunkSend(int chunkCount, int totalChunks, int chunk, int block, int blockChunks, int totalBlocks) {
                if (getBaseSuotaActivity() != null)
                    getBaseSuotaActivity().updateCurrentlySendingInfo(chunkCount, totalChunks, chunk, block, blockChunks, totalBlocks);
            }

            @Override
            public void onUploadProgress(float percent) {
                if (getBaseSuotaActivity() != null)
                    getBaseSuotaActivity().updateProgress(percent);
            }

            @Override
            public void onSuccess(double totalElapsedSeconds, double imageUploadElapsedSeconds) {
                if (getBaseSuotaActivity() == null)
                    return;
                getBaseSuotaActivity().onSuccess(totalElapsedSeconds, imageUploadElapsedSeconds);
                if (!SuotaLibConfig.AUTO_REBOOT)
                    getBaseSuotaActivity().onSuotaFinished();
            }

            @Override
            public void onRebootSent() {
                if (getBaseSuotaActivity() == null)
                    return;
                getBaseSuotaActivity().rebootSent();
                if (SuotaLibConfig.AUTO_REBOOT)
                    getBaseSuotaActivity().onSuotaFinished();
            }
        });
        //suotaManager.setBlockSize(Default.BLOCK_SIZE);
        suotaManager.setSuotaFile(suotaFile);
        suotaManager.setUiContext(context);
        if (suotaFile.isLoaded()) {
            // SPI
            //suotaManager.initializeSuota(Default.BLOCK_SIZE, Default.MISO_GPIO, Default.MOSI_GPIO, Default.CS_GPIO, Default.SCK_GPIO, Default.IMAGE_BANK);
            // I2C
            //suotaManager.initializeSuota(Default.BLOCK_SIZE, 0x50, Default.SCL_GPIO, Default.SDA_GPIO, Default.IMAGE_BANK);
            suotaManager.connect();
        }
    }
}
